from flask import request

from Info.constants import CLICK_RANK_MAX_NEWS, HOME_PAGE_MAX_NEWS
from Info.modules.index import index_blu
from flask import render_template,current_app

from Info.utils.response_code import RET
from flask import session, jsonify
from Info.models import  User, News, Category

# 主页面
@index_blu.route('/')
def index():
    # 获取新闻分类
    categories = Category.query.all()

    # 获取用户登陆状态
    user_id = session.get('user_id')

    # 排行获取点击数据
    new_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    click_new_list = []
    for new in new_list:
        click_new_list.append(new)

    #用户如果没有登陆则显示首页页面
    if not user_id :
        return render_template('news/index.html',new_list=new_list,categories=categories)
    user = User.query.get(user_id)

    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户不存在')
    return render_template('news/index.html',user=user,new_list=new_list,categories=categories)


# 创建图标
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')

# 新闻分页显示
@index_blu.route('/newlist')
def newlist():
    # 1. 获取参数(分类ｉｄ，页数，每页行数)
    req_dic = request.args
    cid = req_dic.get('cid',1)
    page = req_dic.get('page',1)
    per_page = req_dic.get('per_page',HOME_PAGE_MAX_NEWS)
    # 2. 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='传入参数格式有问题')
    # 3. 查询数据
        根据分类ｉｄ查询数据库
    new_lists = None
    if cid ==1 :
        #     查询数据库所有并按创建时间最新的排序，
        new_lists = News.query.order_by(News.create_time.desc()).paginate(page, per_page, False)
    else:
        new_lists = News.query.filter(News.category_id==cid).order_by(News.create_time).paginate(page,per_page,False)
    # 4. 返回数据
    new_lists_dict = new_lists.items
    news = []
    for new in new_lists_dict:
        news.append(new.to_basic_dict())
    currentPage = new_lists.page
    # 总页数
    totalPage = new_lists.pages
    return jsonify(errno=RET.OK,
                   errmsg='发送成功',
                   cid=cid,
                   totalPage=totalPage,
                   currentPage=currentPage,
                   newsList=news

    )
